extends Chara

var ZHPData = preload("./charaData.gd").getCharaData()#载入主体翻译
var baseId = ""
var charaInfo
var inited = false
var lotteryWindow
const ctrl = globalData.infoDs["g_ZHPLine"]
const base = globalData.infoDs["g_ZHPBase"]
const Utils = globalData.infoDs["g_ZHPUtils"]
const Shop = globalData.infoDs["g_ZHPShop"]

func _init():
	._init()
	self.get_node("ui/hpBar").visible = false

func _extInit():
	._extInit()
	chaName = ZHPData.name
	attCoe.atkRan = 0                 #攻击距离
	attCoe.maxHp = 0.009                  #最大生命（呈现在游戏中时，每点代表112.5，取整数，下同）
	attCoe.atk = 0                    #攻击力（每点代表8.5）
	attCoe.mgiAtk = 0                 #魔法攻击（每点代表13.7）
	attCoe.def = 0                    #物理防御（每点代表15）
	attCoe.mgiDef = 0                 #魔法防御（每点代表16.6）
	lv = 1                           #等级的设置
	atkEff = "atk_dao"                #攻击时的特效
	aiOn = false
	attAdd.cri -= 0.2	
	addSkillTxt(ZHPData.SKILL_TEXT.format({"0":Shop.HandlingFee*Shop.voucher,"1":Shop.RecoveryFloat,"2":Shop.DrinkCosts*Shop.CostReduction*Shop.voucher,"3":Shop.healhp,"4":Shop.roundtiem}))
	if not inited:
		inited = true
		if not is_connected("onPressed", self, "chaInfo"):
			connect("onPressed", self, "chaInfo")
		sys.main.connect("onBattleEnd",self,"BattleEnd")
		sys.main.connect("onBattleReady",self,"BattleReady")

func BattleReady():
	if base.setting.get("CheckMode") == true:
		sys.main.delMatChara(self)

func BattleEnd():
	skillStrs[0] = ZHPData.SKILL_TEXT.format({"0":Shop.HandlingFee*Shop.voucher,"1":Shop.RecoveryFloat,"2":Shop.DrinkCosts*Shop.CostReduction*Shop.voucher,"3":Shop.healhp,"4":Shop.roundtiem})

func _onDeath(atkInfo):
	._onDeath(atkInfo)
	if isDeath == true:
		isSumm = true
		Shop.exist = false
		for i in getAllChas(1):
			i.att.hp = -1000000
			hurtChara(i,0,Chara.HurtType.REAL,Chara.AtkType.EFF)
		if team == 1:
			sys.newBaseMsg("",ZHPData.TEXT_10)
			for i in range(sys.rndRan(5,8)):
				sys.main.player.addItem(sys.newItem(Shop.getRndItemEnd()))

func _upS():
	._upS()

func chaInfo(cha):
	yield(cha.reTimer(0.05),"timeout")
	charaInfo = sys.get_node("/root/topUi/charaInfoMsg")
	var txt = charaInfo.get_node("txt")
	var split = txt.bbcode_text.rsplit("\n")
	var res = ""

	skillStrs[0] = ZHPData.SKILL_TEXT.format({"0":Shop.HandlingFee*Shop.voucher,"1":Shop.RecoveryFloat,"2":Shop.DrinkCosts*Shop.CostReduction*Shop.voucher,"3":Shop.healhp,"4":Shop.roundtiem})

	charaInfo.get_node("Button").hide()#进化按钮隐藏
	reItem(charaInfo)#以旧换新
	sellItem(charaInfo,cha)#旧物收购
	Huixue()#异世界饮料
	Shop(charaInfo)#旧物贩卖
	Equip(charaInfo,cha)#脱下装备
	# Casting(charaInfo,cha)
	
	# 在面板上显示点数
	var pointstext = RichTextLabel.new()
	pointstext.bbcode_enabled = true
	pointstext.bbcode_text = ZHPData.TEXT_9.format({"0":Shop.Points})
	pointstext.rect_min_size = Vector2(200,100)
	pointstext.margin_top = 27
	pointstext.margin_left = 187
	charaInfo.add_child(pointstext)

	for i in range(split.size()):
		if i == 0:
			res += split[i] + "            [color=#66A15F]\n"
		elif i == 1:
			res += ""
		elif i == 2:
			res += ""
		elif i == 3:
			res += ""
		elif i == 4:
			res += ""
		else:
			res += split[i] + "\n"
	yield(cha.reTimer(0.10),"timeout")
	txt.bbcode_text = res

# 创建以旧换新按钮
func reItem(charaInfo):
	if items.size() < 1:return
	if sys.main.isAiStart:return
	if base.setting.get("picture") == true:
		var pbt = TextureButton.new()
		var im = Image.new()
		im.load(ctrl.path+"/other/refresh.png")
		var imt = ImageTexture.new()
		imt.create_from_image(im)
		imt.flags = 4
		pbt.set_normal_texture(imt)
		im = Image.new()
		im.load(ctrl.path+"/other/refresh2.png")
		imt = ImageTexture.new()
		imt.create_from_image(im)
		imt.flags = 4
		pbt.set_pressed_texture(imt)
		charaInfo.add_child(pbt)
		pbt.set_size(Vector2(60,60))
		pbt.set_position(Vector2(100,500))
		pbt.connect("pressed",self,"reItems")
	else:
		Utils.createItemButton(charaInfo,self,ZHPData.BUTTIN_1,"reItems",[],Vector2(100, 550))

# 创建旧物收购按钮
func sellItem(charaInfo,cha):
	if items.size() < 1:return
	if sys.main.isAiStart:return
	if base.setting.get("picture") == true:
		var pbt = TextureButton.new()
		var im = Image.new()
		im.load(ctrl.path+"/other/recovery.png")
		var imt = ImageTexture.new()
		imt.create_from_image(im)
		imt.flags = 4
		pbt.set_normal_texture(imt)
		im = Image.new()
		im.load(ctrl.path+"/other/recovery2.png")
		imt = ImageTexture.new()
		imt.create_from_image(im)
		imt.flags = 4
		pbt.set_pressed_texture(imt)
		charaInfo.add_child(pbt)
		pbt.set_size(Vector2(60,60))
		pbt.set_position(Vector2(300,500))
		pbt.connect("pressed",self,"sellItems",[cha])	
	else:
		Utils.createItemButton(charaInfo,self,ZHPData.BUTTIN_2,"sellItems",[cha],Vector2(300, 550))

# 创建异世界饮料按钮
func Huixue():
	if sys.main.player.hp == sys.main.player.maxHp:return
	if sys.main.isAiStart:return
	if base.setting.get("picture") == true:
		var pbt = TextureButton.new()
		var im = Image.new()
		im.load(ctrl.path+"/other/blood.png")
		var imt = ImageTexture.new()
		imt.create_from_image(im)
		imt.flags = 4
		pbt.set_normal_texture(imt)
		im = Image.new()
		im.load(ctrl.path+"/other/blood2.png")
		imt = ImageTexture.new()
		imt.create_from_image(im)
		imt.flags = 4
		pbt.set_pressed_texture(imt)
		charaInfo.add_child(pbt)
		pbt.set_size(Vector2(60,60))
		pbt.set_position(Vector2(500,500))
		pbt.connect("pressed",self,"yaoshui")	
	else:
		Utils.createItemButton(charaInfo,self,ZHPData.BUTTIN_3,"yaoshui",[],Vector2(500, 550))

# 创建旧物贩卖按钮
func Shop(charaInfo):
	# if Shop.shoptime >= 6:return
	if sys.main.isAiStart:return
	if base.setting.get("picture") == true:
		var pbt = TextureButton.new()
		var im = Image.new()
		im.load(ctrl.path+"/other/sell.png")
		var imt = ImageTexture.new()
		imt.create_from_image(im)
		imt.flags = 4
		pbt.set_normal_texture(imt)
		im = Image.new()
		im.load(ctrl.path+"/other/sell2.png")
		imt = ImageTexture.new()
		imt.create_from_image(im)
		imt.flags = 4
		pbt.set_pressed_texture(imt)
		charaInfo.add_child(pbt)
		pbt.set_size(Vector2(60,60))
		pbt.set_position(Vector2(730,500))
		pbt.connect("pressed",self,"openShop")	
	else:
		Utils.createItemButton(charaInfo,self,ZHPData.BUTTIN_5,"openShop",[],Vector2(730, 550))

# 创建脱下装备按钮
func Equip(charaInfo,cha):
	if items.size() < 1:return
	if sys.main.isAiStart:return
	if base.setting.get("picture") == true:
		var pbt = TextureButton.new()
		var im = Image.new()
		im.load(ctrl.path+"/other/equip.png")
		var imt = ImageTexture.new()
		imt.create_from_image(im)
		imt.flags = 4
		pbt.set_normal_texture(imt)
		im = Image.new()
		im.load(ctrl.path+"/other/equip2.png")
		imt = ImageTexture.new()
		imt.create_from_image(im)
		imt.flags = 4
		pbt.set_pressed_texture(imt)
		charaInfo.add_child(pbt)
		pbt.set_size(Vector2(60,60))
		pbt.set_position(Vector2(1400,500))
		pbt.connect("pressed",self,"removeAllEquip",[cha])	
	else:
		Utils.createItemButton(charaInfo,self,ZHPData.BUTTIN_4,"removeAllEquip",[cha],Vector2(1400, 550))

# func Casting(charaInfo,cha):
# 	if items.size() < 2:return
# 	if sys.main.isAiStart:return
# 	Utils.createItemButton(charaInfo,self,"  铸造  ","dazao",[cha],Vector2(900, 460))

# 以旧换新运行函数
func reItems():
	if items.size() < 1:return
	var x = items.size()
	var y = Shop.HandlingFee
	var i = items.size()-1
	if sys.main.player.gold >= y*Shop.voucher*x:
		Shop.HandlingFee = sys.rndRan(5,20)
		Shop.saveAndLoad("save")
		skillStrs[0] = ZHPData.SKILL_TEXT.format({"0":Shop.HandlingFee*Shop.voucher,"1":Shop.RecoveryFloat,"2":Shop.DrinkCosts*Shop.CostReduction*Shop.voucher,"3":Shop.healhp,"4":Shop.roundtiem})
		charaInfo.queue_free()
		while (i >= 0):
			if items[i] != null and items[i].price > 0:
				sys.main.player.subGold(y*Shop.voucher)
				sys.main.player.addItem(Utils.getRndItem())
				sys.main.player.delItem(items[i])
			i -= 1
		Shop.voucher = 1
		Shop.PointsaveAndload("save")
	else:
		sys.newBaseMsg(ZHPData.TEXT_1,ZHPData.TEXT_2)

# 旧物回收运行函数
func sellItems(cha):
	if items.size() < 1:return
	var index = cha.items.size()-1
	while index >= 0:
		var item = cha.items[index]
		var value = item.price*Shop.RecoveryFloat
		sys.main.player.plusGold(value)
		sys.main.player.delItem(item)
		index -= 1
	Shop.RecoveryFloat = sys.rndRan(1,30)/10 as float
	Shop.saveAndLoad("save")
	skillStrs[0] = ZHPData.SKILL_TEXT.format({"0":Shop.HandlingFee*Shop.voucher,"1":Shop.RecoveryFloat,"2":Shop.DrinkCosts*Shop.CostReduction*Shop.voucher,"3":Shop.healhp,"4":Shop.roundtiem})
	charaInfo.queue_free()

# 异世界药水运行函数
func yaoshui():
	if base.setting.get("zhiyuan") == true:
		sys.newBaseMsg("",ZHPData.TEXT_11)
		return
	# if sys.main.player.hp == sys.main.player.maxHp:return
	if Shop.Points >= Shop.DrinkCosts*Shop.CostReduction*Shop.voucher:
		Shop.Points -= Shop.DrinkCosts*Shop.CostReduction
		Shop.voucher = 1
		sys.main.player.plusHp(Shop.healhp)
		Shop.DrinkCosts = sys.rndRan(1,100)
		Shop.healhp = sys.rndRan(1,Shop.maxheal)
		Shop.saveAndLoad("save")
		Shop.PointsaveAndload("save")
		skillStrs[0] = ZHPData.SKILL_TEXT.format({"0":Shop.HandlingFee*Shop.voucher,"1":Shop.RecoveryFloat,"2":Shop.DrinkCosts*Shop.CostReduction*Shop.voucher,"3":Shop.healhp,"4":Shop.roundtiem})
		charaInfo.queue_free()
	else:
		sys.newBaseMsg(ZHPData.TEXT_4,ZHPData.TEXT_5)

# 脱下装备运行函数
func removeAllEquip(cha):
	charaInfo.queue_free()
	var index = cha.items.size()-1
	while index >= 0:
		cha.delItem(cha.items[index])
		index -= 1
	
# 打造
# func dazao(cha):
# 	var aitem = null
# 	var bitem = null
# 	var citem = null
# 	var itemList = cha.items
# 	if itemList.size() < 2:return
# 	if itemList.size() == 2:
# 		aitem = itemList[0]
# 		bitem = itemList[1]
# 	if itemList.size() == 3:
# 		aitem = itemList[0]
# 		bitem = itemList[1]
# 		citem = itemList[2]
# 		yield(sys.get_tree().create_timer(0.01), "timeout")
# 		delItem(citem)
# 		sys.main.player.delItem(citem)
# 	yield(sys.get_tree().create_timer(0.01), "timeout")
# 	delItem(aitem)
# 	delItem(bitem)
# 	sys.main.player.delItem(aitem)
# 	sys.main.player.delItem(bitem)	
# 	sys.main.player.addItem(Utils.getRndItem())

var eventShop

# 旧物贩卖运行函数
func openShop():
	eventShop = sys.newMsg("jiangLiMsg")
	eventShop.get_node("Panel/Label").text = ZHPData.BUTTIN_5
	var panel = eventShop.get_node("Panel")

	# 刷新计时
	var retext = RichTextLabel.new()
	retext.bbcode_enabled = true
	retext.bbcode_text = ZHPData.TEXT_3.format({"0":Shop.roundtiem})
	retext.rect_min_size = Vector2(400,100)
	retext.margin_top = 520
	retext.margin_left = 80
	eventShop.get_node("Panel").add_child(retext)

	# 点数
	var bondtext = RichTextLabel.new()
	bondtext.bbcode_enabled = true
	bondtext.bbcode_text = ZHPData.TEXT_9.format({"0":Shop.Points})
	bondtext.rect_min_size = Vector2(200,100)
	bondtext.margin_top = 520
	bondtext.margin_left = 900
	eventShop.get_node("Panel").add_child(bondtext)

	# 在商店刷新之前买完6件物品后给出的文字
	if Shop.shoptime >= 6:
		var restocking = RichTextLabel.new()
		restocking.bbcode_enabled = true
		restocking.bbcode_text = ZHPData.TEXT_7
		restocking.rect_min_size = Vector2(300,100)
		restocking.margin_top = 320
		restocking.margin_left = 60
		eventShop.get_node("Panel").add_child(restocking)

	# 手动刷新商品
	var refresh = RichTextLabel.new()
	refresh.bbcode_enabled = true
	refresh.bbcode_text = ZHPData.TEXT_8_1.format({"0":300*Shop.CostReduction*Shop.voucher})
	refresh.rect_min_size = Vector2(300,100)
	refresh.margin_top = 360
	refresh.margin_left = 920
	eventShop.get_node("Panel").add_child(refresh)
	Utils.createItemButton(eventShop,self,ZHPData.BUTTIN_6,"refresh",[],Vector2(1180, 420))

	var gridList = GridContainer.new()
	gridList.columns = 6#一行放几个商品
	gridList.rect_position = Vector2(55,80)
	panel.add_child(gridList)
	eventShop.popup()#显示商品界面
	loadItems(gridList)#加载商品

func loadItems(gridList):
	for key in Shop.eventItems.keys():
		var item = Shop.eventItems.get(key)

		var itemPanel = Panel.new()
		itemPanel.name = "panel"
		itemPanel.rect_min_size = Vector2(170, 230)

		var obj
		if item.type == "func":
			obj = TextureRect.new()
			obj.set_texture(base.loadImg(Utils.path, item.img))
		elif item.type == "item":
			obj = preload("res://ui/item/item.tscn").instance()
			var items = sys.newItem(item.objId)
			obj.init(items)
			obj.isDrag = false
			obj.rect_position = Vector2(60, 70)
		elif item.type == "cha":
			obj = preload("res://ui/itemBt/itemBt.tscn").instance()
			var items = sys.main.newChara(item.objId)
			obj.init(items)
			# obj.isDrag = false
			obj.rect_position = Vector2(5, 10)

		itemPanel.add_child(obj)

		# 可购买次数
		var textLab = Label.new()#价格label
		textLab.align = 1#对齐方式，1是居中对齐
		if item.number == 0:#剩余次数为0的文本显示
			textLab.text = ZHPData.TEXT_6
		elif item.number == 1:#剩余次数为1的文本显示
			textLab.text = " "
		textLab.rect_position = Vector2(50, 20)
		itemPanel.add_child(textLab)

		# 价格
		var itemLab = Label.new()#价格label
		itemLab.align = 1#对齐方式，1是居中对齐
		if item.number == 0:#剩余次数为0的价格显示
			itemLab.text = " "
		elif item.number == 1:#剩余次数为1的价格显示
			itemLab.text = "{0}".format({"0":item.price*Shop.CostReduction*Shop.voucher})
		itemLab.rect_position = Vector2(65, 120)
		itemPanel.add_child(itemLab)

		if item.number != 0:
			createItemButton(itemPanel, item.btnText, item.conn, [item])

		gridList.add_child(itemPanel)

#创建购买商品按钮
func createItemButton(baseNode, text, callback, args=[]):
	var b = Button.new()
	b.rect_position = Vector2(100, 165)
	b.text = text

	b.connect("pressed", self, callback, args)
	baseNode.add_child(b)

	return b

#购买物品
signal buyItem
func buyItem(conf):
	var xxx = conf.price*Shop.CostReduction*Shop.voucher#商品价格*费用倍率(倍率默认为1，学习天赋后为0.8)
	if Shop.Points < xxx:
		sys.newBaseMsg(ZHPData.TEXT_4, ZHPData.TEXT_5)
		return
	if conf.type == "item":
		var item = sys.newItem(conf.objId)
		sys.main.player.addItem(item)
	elif conf.type == "cha":
		var item = sys.main.newChara(conf.objId)
		sys.main.player.addCha(item)
	Shop.Points -= xxx
	Shop.voucher = 1
	conf.number -= 1
	Shop.shoptime += 1
	Shop.saveAndLoad("save")
	Shop.ItemsaveAndLoad("save")
	Shop.PointsaveAndload("save")
	eventShop.queue_free()
	openShop()
	emit_signal("buyItem")

func refresh():
	if Shop.Points < 300*Shop.CostReduction*Shop.voucher:
		sys.newBaseMsg(ZHPData.TEXT_4_1, ZHPData.TEXT_5_1)
		return
	Shop.Points -= 300*Shop.CostReduction*Shop.voucher
	Shop.voucher = 1
	Shop.Refresh()
	eventShop.queue_free()
	openShop()